<template>
    <view class="camera-container">
      <camera
        device-position="front"
        flash="auto"
        @error="error"
        class="camera"
      ></camera>
      
      <view class="controls">
        <view class="btn cancel" @click="cancel">取消</view>
        <view class="btn capture" @click="takePhoto">拍照</view>
        <view class="btn switch" @click="switchCamera">切换</view>
      </view>
    </view>
  </template>
  
  <script>
  export default {
    data() {
      return {
        cameraPosition: 'front' // front 前置，back 后置
      }
    },
    methods: {
      takePhoto() {
        const ctx = uni.createCameraContext()
        ctx.takePhoto({
          quality: 'high',
          success: (res) => {
            // 返回拍照路径给上一页面
            const eventChannel = this.getOpenerEventChannel()
            eventChannel.emit('takePhotoSuccess', res.tempImagePath)
            uni.navigateBack()
          },
          fail: () => {
            uni.showToast({
              title: '拍照失败',
              icon: 'none'
            })
          }
        })
      },
      
      switchCamera() {
        this.cameraPosition = this.cameraPosition === 'front' ? 'back' : 'front'
      },
      
      cancel() {
        uni.navigateBack()
      },
      
      error(e) {
        uni.showToast({
          title: '相机调用失败',
          icon: 'none'
        })
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .camera-container {
    width: 100vw;
    height: 100vh;
    background: #000;
    position: relative;
    
    .camera {
      width: 100%;
      height: 100%;
    }
    
    .controls {
      position: fixed;
      bottom: 50rpx;
      left: 0;
      right: 0;
      display: flex;
      justify-content: space-around;
      align-items: center;
      padding: 0 40rpx;
      
      .btn {
        color: #fff;
        font-size: 32rpx;
        padding: 20rpx 40rpx;
        border-radius: 40rpx;
        
        &.capture {
          width: 120rpx;
          height: 120rpx;
          border-radius: 50%;
          background: rgba(255,255,255,0.8);
          display: flex;
          align-items: center;
          justify-content: center;
          color: #333;
        }
        
        &:active {
          opacity: 0.8;
        }
      }
    }
  }
  </style>